﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;
using System.Reflection;
using System.IO;

namespace ImageTagToolViewModel.Data
{
    /// <summary>
    /// Singleton class for handling the database connection
    /// </summary>
    public class DatabaseConnector
    {
        /// <summary>
        /// Stores the DatabaseConnector instance
        /// </summary>
        private static DatabaseConnector myInstance;

        /// <summary>
        /// Stores the database connection object
        /// </summary>
        private SqlCeConnection myConnection;

        /// <summary>
        /// Returns the connection object
        /// </summary>
        public SqlCeConnection Connection
        {
            get
            {
                return myConnection;
            }
        }

        /// <summary>
        /// Gets the DatabaseConnector instance
        /// </summary>
        public static DatabaseConnector Instance
        {
            get
            {
                object locker = new object();
                lock (locker)
                {
                    if (myInstance == null)
                        myInstance = new DatabaseConnector();
                }
                return myInstance;
            }
        }

        /// <summary>
        /// Initializes the connection object
        /// </summary>
        private DatabaseConnector()
        {
            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            myConnection = new SqlCeConnection("Data Source=" + Path.Combine(path, @"Data\ImageTagToolDB.sdf"));
        }

        /// <summary>
        /// Connects to the database
        /// </summary>
        public void Connect()
        {
            if (myConnection.State == System.Data.ConnectionState.Closed)
            {
                myConnection.Open();
            }            
        }

        /// <summary>
        /// Disconnects from the database
        /// </summary>
        public void Disconnect()
        {
            myConnection.Close();
        }

    }
}
